package com.kld.shop.controller.webController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.dto.TreeNode;
import com.kld.common.framework.global.Global;
import com.kld.common.redis.JedisManager;
import com.kld.common.util.JsonUtil;
import com.kld.common.util.RedisUtil;
import com.kld.order.api.IOrderItemService;
import com.kld.order.api.IOrderService;
import com.kld.order.api.SubOrderService;
import com.kld.product.api.IProProductService;
import com.kld.product.po.ProCategory;
import com.kld.product.po.ProProduct;
import com.kld.product.po.Product;
import com.kld.shop.controller.base.BaseWebController;
import com.kld.sys.api.ISysDictService;
import com.kld.sys.api.ImgsService;
import com.kld.sys.po.Imgs;
import com.kld.sys.po.SysDict;
import com.kld.third.api.jingdong.IJdProductService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Dan on 2015/8/6.
 *
 * problems:
// 1 TaskOrderSplit
// 2 TaskOrderState
 3 iProProductService.getProductDetail()
 4 iProProductService.getCategoryTree()
 5 iProProductService.getHotProductListNew(8)
 6 categoryService.getLv1CateTreeByCode(catecode)
 7 categoryService.getCodesByLevelAndPcode
 8 categoryService.getCodesList(cateMap)
 9 categoryService.getAllLv3CateList(ccode)
 10 iProProductService.findProductList(map) 带分页
 11 iProProductService.setPIntro()
 12 getTreeNode()
 13 iProProductService.getPromotionProList
 */
@Controller
@RequestMapping("product")
public class ProductWebController extends BaseWebController {

    @Resource
    private IProProductService iProProductService;

    @Resource
    private ISysDictService iSysDictService;


    @Resource
    private ImgsService imgsService;

//    @Resource
//    private IProCateGoryService categoryService;
//
//    @Resource
//    private IJdProductService iJdProductService;

    // TODO: 2016/3/30 task相关的没有实现 
//    @Autowired
//    private TaskOrderSplit taskOrderSplit;
//    @Autowired
//    private TaskOrderState taskOrderState;
//    @Resource
//    private IOrderService iOrderService;
//    @Resource
//    private SubOrderService subOrderService;
//    @Resource
//    private IOrderItemService iOrderItemService;




    @ResponseBody
    @RequestMapping("splitorder")
    public ResultMsg splitOrder()
    {
        //订单拆单消息处理
        //收到拆单消息后，调用京东查询订单接口，更新订单信息，记录子订单号
        // TODO: 2016/3/30 task caoz
//        taskOrderSplit.orderSplit(Global.TASK_MERCHANT_NAME, Global.JD_MESSAGE_DELTYPE);
        return new ResultMsg();
    }


    @RequestMapping("/proinfo")
    public ModelAndView productDetail() {
        String proid=request.getParameter("proid");
        // TODO: 2016/3/30  
//        Product p= iProProductService.getProductDetail(Integer.parseInt(proid),false);
        ProProduct p = null;
        try{
            p = iProProductService.selectByPrimaryKey(Integer.parseInt(proid));
        }catch (Exception e){
            logger.error("获得商品错误"+e.getMessage(),e);
        }

        Map<String,Object> map = new HashMap<String,Object>();
        Object category = JedisManager.getObject(Global.INDEX_CATEGORY);
        if(category == null){
            //不知道这个getCategoryTree怎么获得的。
            // TODO: 2016/3/30
//            category = iProProductService.getCategoryTree();
            category = "";
            JedisManager.setObject("category",6000,category);
        }
        Object hotproduct = JedisManager.getObject(Global.INDEX_HOTPRODUCT);
        if(hotproduct == null){
            // TODO: 2016/3/30
//            hotproduct =  iProProductService.getHotProductListNew(8);
            hotproduct = "";
            JedisManager.setObject("hotproduct",6000,hotproduct);
        }
        map.put("category",category);
        map.put("hotproduct",hotproduct);
        map.put("product", p);
        return new ModelAndView("proinfo",map);
    }

    @RequestMapping("/prolist")
    public ModelAndView productList() {
        Map<String,Object> resultmap = new HashMap<String,Object>();
        String catecode = request.getParameter("catecode");
        String question = request.getParameter("question");
        String  cstmtype =request.getParameter("cstmtype");
        String v = request.getParameter("v");
        //积分筛选参数标志
        String topSPoints =request.getParameter("topSPoints");
        //返回类别信息
        if(StringUtils.isNotBlank(catecode)){
            // TODO: 2016/3/30
//            resultmap.put("currcatetree", categoryService.getLv1CateTreeByCode(catecode));
            logger.info("商品列表导航类别"+catecode+"==>"+String.format("%s", JSONObject.fromObject(resultmap.get("currcatetree"))));
        }
        // TODO: 2016/3/30
//        resultmap.put("category", iProProductService.getCategoryTree());
        Jedis jedis = new RedisUtil().getJedis();
        if(StringUtils.isNotBlank(question)){
            resultmap.put("question", question);
        }
        if(StringUtils.isNotBlank(topSPoints)){
            resultmap.put("topSPoints", topSPoints);
            resultmap.put("sPoints", topSPoints);
        }
        if(StringUtils.isNotBlank(v)){
            resultmap.put("v", v);
        }
        //根据用户类型排序（1、车队按积分倒序；2普通用户按积分正序排）
        if(StringUtils.isNotBlank(cstmtype)){
            String orderby = "";
            if("1".equals(cstmtype)){
                orderby="pointsasc";
            }else if("2".equals(cstmtype)){
                orderby = "pointsdesc";
            }
            if(StringUtils.isNotBlank(orderby)){
                resultmap.put("orderby",orderby);
            }
        }
        //获取价格选择
        SysDict sysDict = iSysDictService.getSysDictByAlias("jfsx");
        resultmap.put("points_select", iSysDictService.getSysDictListByPcode(sysDict.getDictcode()));

        //返回猜你喜欢商品列表
        if(jedis!=null){
            resultmap.put("hotproduct",
                    // TODO: 2016/3/30
//                    new RedisUtil().isExists(Global.PROLIST_HOTPRODUCT) ? JsonUtil.listtoJSONArray(new RedisUtil().getValue(Global.PROLIST_HOTPRODUCT)) : iProProductService.getHotProductList(10));
                    "aaaaaaaa");

            //获取商品分类信息（树结构）
            resultmap.put("category",
                    // TODO: 2016/3/30
//                    new RedisUtil().isExists(Global.INDEX_CATEGORY) ?  JsonUtil.listtoJSONArray(new RedisUtil().getValue(Global.INDEX_CATEGORY)): iProProductService.getCategoryTree());
                    "aaaaaaaa");
        }else {
            resultmap.put("hotproduct",
                    //// TODO: 2016/3/30
                    "这里该有热销产品列表");
//                     iProProductService.getHotProductList(10));

            //获取商品分类信息（树结构）
            resultmap.put("category",
                    // TODO: 2016/3/30
                    "这里该有树结构");
//                    iProProductService.getCategoryTree());
        }
//        resultmap.put("count",count);
        response.setCharacterEncoding("utf-8");
        return new ModelAndView("prolist",resultmap);
    }

    /**
     * 获取热兑商品信息
     */
    @ResponseBody()
    @RequestMapping("getHotProductList")
    public List<Product> getHotProductList(){
        // TODO: 2016/3/30
        return null;
//        return iProProductService.getHotProductList(10);
    }

    /**
     * 获取热兑品类信息
     * @return
     */
    @ResponseBody()
    @RequestMapping("getHotCategoryList")
    public List<ProCategory> getHotCategoryList(){
        return null;
//        return iProProductService.getHotCategoryList(8);
    }

    /**
     * 查询条件：
     * 1、catecode 按分类级别准确查询（1、2、3级;注：1、2级需要查询所有3级分类；最终根据3级类别准确查找）
     * 2、sPoints   按积分范围查询（参数：例（1000，1999））
     * 3、q         模糊查询（按照商品、或者商品类别名称）
     */
    @ResponseBody()
    @RequestMapping(value = "getProductList" )
    public ResultMsg getProductList(){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            logger.info("获取商品列表失败",e);
        }
        response.setContentType("text/html;charset=utf-8");
        ResultMsg rmsg = new ResultMsg();
        Map<String,Object> map = new HashMap<String, Object>();
        Map<String,Object> cmap = new HashMap<String, Object>();
        List<String> categorys = new ArrayList<String>();
        String catecode = request.getParameter("catecode");
        String question = request.getParameter("question");
        String points = request.getParameter("sPoints");
        String sorderby = request.getParameter("orderby");

        TreeNode treeNode = new TreeNode();

        //查询条件
        //1、根据积分筛选
        if(StringUtils.isNotBlank(points)){
            if(",".equals(points.substring(0,1))){//<=
                map.put("point1",Integer.parseInt(points.substring(1,points.length()).trim()));
            }else if(",".equals(points.substring(points.length()-1, points.length()) )){//>=
                map.put("point2",Integer.parseInt(points.substring(0, points.length() - 1).trim()));
            }else{
                String[] p = points.split(",");
                if(p!=null && p.length>=2){
                    map.put("point1",Integer.parseInt(p[1].trim()));
                    map.put("point2",Integer.parseInt(p[0].trim()));
                }
            }
        }


        //2根据商品类别筛选
        if(StringUtils.isNotBlank(catecode)){
            // TODO: 2016/3/30 获取类别
//            ProCateGory category = iProProductService.selectCategoryByCode(catecode);
            ProCategory category = null;
            String codes="";

            if(category!=null) {
                if (category.getLev().equals(3)) {
                    // TODO: 2016/3/30 没有这个编码。 
//                    categorys.add(category.getCode());

                } else if (category.getLev() >= 1 && category.getLev() < 3) {
                    cmap.put("level",category.getLev());
                    // TODO: 2016/3/30  
//                    cmap.put("code",category.getCode());
//                    categorys = categoryService.getCodesByLevelAndPcode(cmap);
                }
                map.put("catecodes", categorys);
            }
            //返回catecode
            treeNode = getTreeNode(catecode);
            rmsg.setData(treeNode);
        }

        //3、模糊查询条件，根据商品名称、类别名称
        if(StringUtils.isNotBlank(question)){
            map.put("qname", question);
            Map<String,Object> cateMap = new HashMap<String, Object>();
            cateMap.put("question",question);
            // TODO: 2016/3/30  
//            List<String> catecodes = categoryService.getCodesList(cateMap);
            List<String> catecodes = null;
            Iterator<String> iterCate = catecodes.iterator();
            List<String> qCatecodes = new ArrayList<String>();
            while (iterCate.hasNext()){
                String ccode = iterCate.next();
                // TODO: 2016/3/30  
//                qCatecodes.addAll(qCatecodes.size(),categoryService.getAllLv3CateList(ccode));
            }
            map.put("qcatecodes",qCatecodes);
        }
        //4、根据上架状态筛选
        map.put("state",1);

        //排序方式
        if(StringUtils.isNotBlank(sorderby)){ map.put("sorderby",sorderby);}
        PageHelper.startPage(getPageNum(), getPageSize());
        // TODO: 2016/3/30  
        return null;
//        List<Product> productList = iProProductService.findProductList(map);
//        PageInfo pageInfo = new PageInfo(productList);
//       /* rmsg.setResult(true);
//        rmsg.setTotal(productList.size());
//        rmsg.setRows(productList);*/
//        return PageInfoResult.PageInfoMsg(pageInfo);
    }

    @ResponseBody()
     @RequestMapping("getProductDetail")
     public Product getProductDetail(Integer proid){
        // TODO: 2016/3/30  
        return null;
//        Product product = iProProductService.getProductDetail(proid, false);
//        return product;
    }

    @ResponseBody()
    @RequestMapping("category")
    public List get(String code){
        Jedis jedis = new RedisUtil().getJedis();
        List list = new ArrayList();
        // TODO: 2016/3/30  
//        if(jedis!=null){
//            list=JsonUtil.listtoJSONArray(new RedisUtil().isExists(Global.INDEX_CATEGORY) ?  JsonUtil.listtoJSONArray(new RedisUtil().getValue(Global.INDEX_CATEGORY)): iProProductService.getCategoryTree());
//        }else{
//            list=JsonUtil.listtoJSONArray(iProProductService.getCategoryTree());
//        }

        return list;
    }


    public TreeNode getTreeNode(String catecode) {
        return new TreeNode();
        // TODO: 2016/3/30  
//        List<TreeNode> nodes = new ArrayList<TreeNode>();
//        List<TreeNode> nodes1 = new ArrayList<TreeNode>();
//        Category category = categoryService.selectCategoryByCode(catecode);
//        TreeNode treeNode = new TreeNode();
//        TreeNode treeNode1 = new TreeNode();
//        TreeNode treeNode2 = new TreeNode();
//        if (category != null && category.getCategorylevel() == 1) {
//            treeNode = new TreeNode();
//            treeNode.setId(category.getCode());
//            treeNode.setPid(category.getParentcode());
//            treeNode.setText(category.getCategoryname());
//        } else if (category != null && category.getCategorylevel() == 2) {
//            treeNode = new TreeNode();
//            treeNode.setId(category.getCode());
//            treeNode.setPid(category.getParentcode());
//            treeNode.setText(category.getCategoryname());
//            nodes.add(treeNode);
//            Category category1 = categoryService.selectCategoryByCode(category.getParentcode());
//            if (category1 != null) {
//                treeNode1 = new TreeNode();
//                treeNode1.setId(category1.getCode());
//                treeNode1.setPid(category1.getParentcode());
//                treeNode1.setText(category1.getCategoryname());
//                treeNode1.setChildren(nodes);
//            }
//        } else {
//            treeNode = new TreeNode();
//            treeNode.setId(category.getCode());
//            treeNode.setPid(category.getParentcode());
//            treeNode.setText(category.getCategoryname());
//            nodes.add(treeNode);
//            Category category1 = categoryService.selectCategoryByCode(category.getParentcode());
//            if (category1 != null) {
//                treeNode1 = new TreeNode();
//                treeNode1.setId(category1.getCode());
//                treeNode1.setPid(category1.getParentcode());
//                treeNode1.setText(category1.getCategoryname());
//                treeNode1.setChildren(nodes);
//                nodes1.add(treeNode1);
//                Category category2 = categoryService.selectCategoryByCode(category1.getParentcode());
//                if (category2 != null) {
//                    treeNode2 = new TreeNode();
//                    treeNode2.setId(category2.getCode());
//                    treeNode2.setPid(category2.getParentcode());
//                    treeNode2.setText(category2.getCategoryname());
//                    treeNode2.setChildren(nodes1);
//                }
//            }
//        }
//        if(category.getCategorylevel() == 1){
//            return treeNode;
//        }else if(category.getCategorylevel() == 2){
//            return treeNode1;
//        }else{
//            return treeNode2;
//        }

    }


    /**
     * 批量检查商品库存是否有货
     * @param productsinfo 第三方商品编码thirdcode及数量 （例：11:2,22:3）
     * @param area 区域（例：13_23_333  下划线分割标识一级、二级、三级地址）
     * @return
     */
    @ResponseBody()
    @RequestMapping("checkProductStock")
    public ResultMsg checkProductStock(String productsinfo, String area){
        ResultMsg rmsg = new ResultMsg();
        String[] products = productsinfo.split(",");
        if(products==null || products.length==0){
            rmsg.setResult(false);
            rmsg.setMsg("无商品信息");
            return rmsg;
        }
        JSONArray jsonArray = new JSONArray();
        for(String p: products){
            String[] pinfo = p.split(":");
            if(pinfo.length!=2){
                rmsg.setResult(false);
                rmsg.setMsg("商品信息有误！无法查询");
                return rmsg;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("skuId",pinfo[0]);
            jsonObject.put("num",pinfo[1]);
            jsonArray.add(jsonObject);
        }
        // TODO: 2016/3/30  
//        rmsg = iJdProductService.getStockOrder(jsonArray.toString(), area);
        return rmsg;
    }

    @ResponseBody()
    @RequestMapping("setPIntro")
    public ResultMsg setProductIntro(){
        return null;
        // TODO: 2016/3/30  
//        return iProProductService.setPIntro();
    }

    //获取价格选择(积分段)
    @ResponseBody()
    @RequestMapping("/points_select")
    public  ResultMsg getpoints(){
        ResultMsg msg=new ResultMsg();
        SysDict sysDict = iSysDictService.getSysDictByAlias("jfsx");
        msg.setData(iSysDictService.getSysDictListByPcode(sysDict.getDictcode()));
        return  msg;
    }

    //跳转新春钜惠页面
    @RequestMapping("getNewProlist")
    public ModelAndView getNewProlist(){
        String actid=request.getParameter("actid");
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("actid",actid);
        Imgs imgs5 = imgsService.getPrimaryImg(new BigDecimal(actid),5);
        Imgs imgs6 = imgsService.getPrimaryImg(new BigDecimal(actid),6);
        Imgs imgs7 = imgsService.getPrimaryImg(new BigDecimal(actid),7);
        Imgs imgs11 = imgsService.getPrimaryImg(new BigDecimal(actid),11);
        if(null != imgs5){
            map.put("WebItemBannerimg",imgs5.getPicurl());
        }
        if(null != imgs6){
            map.put("WebItemBackgroundimg",imgs6.getPicurl());//这个应该是pick
        }
        if(null != imgs7){
            map.put("WebItemBackgroundcolor",imgs7.getPicurl());
        }
        if(null != imgs11){
            map.put("WebItemListBackgroundcolor",imgs11.getPicurl());
        }
        return new ModelAndView("newActivity",map);
    }

    //获取促销商品列表
    @ResponseBody()
    @RequestMapping("getPromotionProList")
    public ResultMsg getPromotionProList(){
        ResultMsg result=new ResultMsg();
        Map<String,Object> map=new HashMap<String, Object>();
        String actid=request.getParameter("actid");

        if(StringUtils.isNotBlank(actid)){
            map.put("actid",actid);
        }
        return null;
        // TODO: 2016/3/30  
//        PageHelper.startPage(getPageNum(), getPageSize());
//        List<Product> productList = iProProductService.getPromotionProList(map);
//        PageInfo pageInfo = new PageInfo(productList);
//        return PageInfoResult.PageInfoMsg(pageInfo);
    }
}
